<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Animal;
use App\Models\Article;
use App\Models\Category;
use App\Models\Circle;
use App\Services\BalanceService;
use App\Services\CircleDimSearchService;
use App\Services\IdCardService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AnimalController extends BaseController
{
    protected $model = Animal::class;

    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $user_id = $request->input('user_id') ?: $this->getUserId();
        $users = Animal::where('user_id', $user_id)->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($users);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'gender' => 'required',
            'category_id' => 'required',
            'birthday' => 'required',
        ]);
        $input = $request->input();
        $id = $request->input('id');
        $category = Category::find($input['category_id']);
        if (!$category)
            return $this->failed('品种不存在');

        $user = $this->getUser();
        $user_id = $user->id ?? 0;
        if (!$user_id)
            return abort(401);

        $cache_key = 'animal_store_user_id_' . $user_id;
        if (Redis::setnx($cache_key, 1)) {
            Redis::expire($cache_key, 15);
            try {
                $input['category_title'] = $category->title;
                $input['parent_category_id'] = $category->parent_id;
                $input['user_id'] = $user_id;
                if (!empty($input['birthday'])) {
                    $input['birthday_md'] = date('m-d', strtotime($input['birthday']));
                }
                if ($id) {
                    $info = Animal::find($id);
                    if (!$info)
                        return $this->failed('宠物不存在');

                    if ($info->birthday != $input['birthday'] || $info->gender != $input['gender'])
                        $input['id_card'] = IdCardService::handle($input['birthday'], $input['gender']);

                    $info->update($input);
                } else {
                    $input['id_card'] = IdCardService::handle($input['birthday'], $input['gender']);
                    $animal = Animal::create($input);
                    $id = $animal->id;

                    $user->increment('animal_count');

                    BalanceService::id_card($user_id);
                    //生成一条动态  https://shimo.im/mindmaps/wHVrj3vCXT9QVH89

                    if (isset($input['width'])) { //2.0版本
                        $city = $request->input('city');
                        if (!$city) {
                            $address = $user->address;
                            if ($address) {
                                $arr = explode("/", $address);
                                $city = $arr[1];
                            }
                        }
                        $arr_id = [];
                        $cat_map = cate_map();
                        $cate_title = $animal->category_title;
                        if ($city) {
                            $circle = Circle::where('is_area', 1)->where('city', $city)->where('id', '<=', 371)->first();
                            $circle && array_push($arr_id, $circle->id);

                            if (in_array($animal->parent_category_id, [Animal::CAT, Animal::DOG])) {

                                if (in_array($animal->parent_category_id, [Animal::CAT])) {
                                    $circle = Circle::where('is_area', 1)->where('city', $city)->where('title', 'like', '%猫咪%')->where('id', '<=', 3065)->first();
                                    $circle && array_push($arr_id, $circle->id);
                                } else if (in_array($animal->parent_category_id, [Animal::DOG])) {
                                    $circle = Circle::where('is_area', 1)->where('city', $city)->where('title', 'like', '%狗狗%')->where('id', '<=', 3065)->first();
                                    $circle && array_push($arr_id, $circle->id);
                                }


                                if (isset($cat_map[$cate_title]))
                                    $cate_title = $cat_map[$cate_title];

                                $circle = Circle::where('title', 'like', '%'.$cate_title.'%')->first();
                                $circle && array_push($arr_id, $circle->id);
                            } else {
                                $dim_circle_id = CircleDimSearchService::handle($cate_title);
                                $dim_circle_id && array_push($arr_id, $dim_circle_id);
                            }
                        } else {
                            if (in_array($animal->parent_category_id, [Animal::CAT])) {
                                array_push($arr_id, 2289);
                            } else if (in_array($animal->parent_category_id, [Animal::DOG])) {
                                array_push($arr_id, 2288);
                            }
                            if (in_array($animal->parent_category_id, [Animal::CAT, Animal::DOG])) {
                                $cate_title = $animal->category->title ?? '';
                                if (isset($cat_map[$cate_title]))
                                    $cate_title = $cat_map[$cate_title];

                                $circle = Circle::where('title', 'like', '%'.$cate_title.'%')->first();
                                $circle && array_push($arr_id, $circle->id);
                            } else {
                                $dim_circle_id = CircleDimSearchService::handle($cate_title);
                                $dim_circle_id && array_push($arr_id, $dim_circle_id);
                            }
                        }
                        $desc = $request->input('desc');
                        if (!$desc)
                            $desc = '请叫我' . $input['title'];

                        $param = [
                            'title' => $desc,
                            'file_path' => json_encode_cn([
                                [
                                    'w' => $input['width'],
                                    'h' => $input['height'],
                                    'url' => $input['logo']
                                ]
                            ]),
                            'longitude' => $input['longitude'] ?? null,
                            'latitude' => $input['latitude'] ?? null,
                            'type' => Article::TYPE_IMAGE,
                            'is_join_album' => 1,
                            'circle_ids' => implode(",", $arr_id)
                        ];
                        $article = new ArticleController();
                        $article->store($request, $param);
                    }

                }
                Redis::del($cache_key);
                return $this->success(['id' => $id]);
            } catch (\Exception $e) {
                Redis::del($cache_key);
                \Log::error($e->getMessage());
                return $this->failed($e->getMessage());
            }
        }
    }

    public function info(Request $request)
    {
        $this->validate($request, [
            'id' => 'required'
        ]);
        $id = $request->input('id');
        $info = Animal::find($id);
        if (!$info)
            return $this->failed('宠物不存在');
        return $this->success($info);
    }

    public function _after_delete() {
        $user = $this->getUser();
        $user->decrement('animal_count');
    }
}

